package com.ruoyi.web.controller.boc;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.CSVUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.boc.domain.BocActivityPublish;
import com.ruoyi.boc.service.IBocActivityPublishService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 活动发布Controller
 * 
 * @author ruoyi
 * @date 2024-07-18
 */
@RestController
@RequestMapping("/boc/publish")
public class BocActivityPublishController extends BaseController
{
    @Value("${ruoyi.profile}")
    private String uploadPath;

    @Autowired
    private ServerConfig serverConfig;


    @Autowired
    private IBocActivityPublishService bocActivityPublishService;

    /**
     * 查询活动发布列表
     */
    @PreAuthorize("@ss.hasPermi('boc:publish:list')")
    @GetMapping("/list")
    public TableDataInfo list(BocActivityPublish bocActivityPublish)
    {
        startPage();
        List<BocActivityPublish> list = bocActivityPublishService.selectBocActivityPublishList(bocActivityPublish);
        return getDataTable(list);
    }

    /**
     * 导出活动发布列表
     */
    @PreAuthorize("@ss.hasPermi('boc:publish:export')")
    @Log(title = "活动发布", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BocActivityPublish bocActivityPublish)
    {
        List<BocActivityPublish> list = bocActivityPublishService.selectBocActivityPublishList(bocActivityPublish);
        ExcelUtil<BocActivityPublish> util = new ExcelUtil<BocActivityPublish>(BocActivityPublish.class);
        util.exportExcel(response, list, "活动发布数据");
    }

    /**
     * 获取活动发布详细信息
     */
    @PreAuthorize("@ss.hasPermi('boc:publish:query')")
    @GetMapping(value = "/{activityId}")
    public AjaxResult getInfo(@PathVariable("activityId") Long activityId)
    {
        return success(bocActivityPublishService.selectBocActivityPublishByActivityId(activityId));
    }

    /**
     * 新增活动发布
     */
    @PreAuthorize("@ss.hasPermi('boc:publish:add')")
    @Log(title = "活动发布", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BocActivityPublish bocActivityPublish) throws IOException, WriterException {
        String activitySn = "hd"+ DateUtils.dateTimeNow();
        bocActivityPublish.setActivitySn(activitySn);
        bocActivityPublish.setCreateBy(getUsername());
        String sqrcode ="/profile/upload//qrCode/"+activitySn+"s.PNG";
        String eEqrcode ="/profile/upload//qrCode/"+activitySn+"e.PNG";
        drawQrCode(activitySn+"s",300,300);
        drawQrCode(activitySn+"e",300,300);
        bocActivityPublish.setActivitySqrcode(sqrcode);
        bocActivityPublish.setActivityEqrcode(eEqrcode);
        return toAjax(bocActivityPublishService.insertBocActivityPublish(bocActivityPublish));
    }

    /**
     * 修改活动发布
     */
    @PreAuthorize("@ss.hasPermi('boc:publish:edit')")
    @Log(title = "活动发布", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BocActivityPublish bocActivityPublish) throws IOException, WriterException {
        bocActivityPublish.setUpdateBy(getUsername());
        String activitySn = bocActivityPublish.getActivitySn();
        String sqrcode ="/profile/upload//qrCode/"+activitySn+"s.PNG";
        String eEqrcode ="/profile/upload//qrCode/"+activitySn+"e.PNG";
        drawQrCode(activitySn+"s",300,300);
        drawQrCode(activitySn+"e",300,300);
        bocActivityPublish.setActivitySqrcode(sqrcode);
        bocActivityPublish.setActivityEqrcode(eEqrcode);
        return toAjax(bocActivityPublishService.updateBocActivityPublish(bocActivityPublish));
    }

    /**
     * 删除活动发布
     */
    @PreAuthorize("@ss.hasPermi('boc:publish:remove')")
    @Log(title = "活动发布", businessType = BusinessType.DELETE)
	@DeleteMapping("/")
    public AjaxResult remove()
    {
        String filePath= uploadPath+"/upload/code/ruoyi-admin.zip";
        File file = new File(filePath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("资源文件已被删除");
            } else {
                System.out.println("资源文件删除失败");
            }
        } else {
            System.out.println("资源文件不存在");
        }
        return toAjax(1);
    }

    private void drawQrCode(String content, int width, int height) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height);
        Path path = Paths.get(uploadPath+"/upload/qrCode/"+content+".PNG");
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
    }

    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        CSVUtils csvUtils=new CSVUtils();//创建配置类的对象
        List<String> csvLines=csvUtils.readCsv(file);//把前端传过来的数据流解析成字符串数组
        for(String csvLine : csvLines){ //循环此字符串数组
            Gson gson = new Gson();
            Type mapType = new TypeToken<Map<String, Object>>(){}.getType(); // 使用Object作为值类型以处理不同类型的数据
            Map<String, Object> maps = gson.fromJson(csvLine, mapType);
            System.out.println((String) maps.get("姓名"));//把刚才转换成功的每一条数据里面的单个数据再存到学生类里。
            System.out.println((String) maps.get("性别"));
            System.out.println((String) maps.get("年龄"));
            System.out.println((String) maps.get("手机号"));
        }
        return success("上传成功");
    }

}
